<template>
  <div class="progress">
    <div class="sc">{{ current | formatTime }}</div>
    <div
      class="progress-box"
      ref="progress-box"
      @touchstart="touchstart"
      @touchmove="touchmove"
      @touchend="touchend"
    >
      <!-- 进度条 -->
      <div class="progress-contain" ref="progress-contain"></div>
      <!-- 拖动按钮 -->
      <div class="dot" ref="dot"></div>
    </div>
    <div class="sc">{{ duration | formatTime }}</div>
  </div>
</template>
<script>
export default {
  props: ["duration", "current"],
  methods: {
    move() {
      let precent = this.current / this.duration;
      // console.log("precent", precent);
      let distance = precent * this.boxWith;
      // 进度条变化
      this.contrainer.style.width = distance + "px";
      // 小球变化
      this.dot.style.transform = `translateX(${distance}px)`;
    },
    touchstart() {
      this.isTouch = true;
    },
    touchmove(e) {
      // console.log("移动的距离", e.touches[0].pageX);
      // this.distance = e.touches[0].pageX - this.boxLeft;
      // console.log("减去后的移动距离", this.distance);
      this.distance = e.touches[0].pageX - this.boxLeft;
      if (this.distance < 0 || this.distance > this.boxWith) return false;
      // 进度条变化
      this.contrainer.style.width = this.distance + "px";
      // 小球变化
      this.dot.style.transform = `translateX(${this.distance}px)`;
    },
    touchend() {
      const time = (this.distance / this.boxWith) * this.duration;
      this.$emit("changeTime", time);
      this.isTouch = false;
    },
  },
  filters: {
    formatTime(data) {
      let m = parseInt(data / 60);
      let s = parseInt(data % 60);
      return `${m > 9 ? m : "0" + m}:${s > 9 ? s : "0" + s}`;
    },
  },
  watch: {
    current() {
      // 歌曲的当前时间改变 控制 进度条 小球移动
      if (this.isTouch) return false;
      this.move();
    },
  },
  mounted() {
    this.boxWith = this.$refs["progress-box"].clientWidth;
    // 播放条左边界距离左边的位置
    this.boxLeft = this.$refs["progress-box"].getBoundingClientRect().left;
    this.contrainer = this.$refs["progress-contain"];
    // 获取小球
    this.dot = this.$refs["dot"];
    this.isTouch = false;
  },
};
</script>
<style lang="less" scoped>
@import "styles/index.less";
.progress {
  .margin-top(60);
  .sc {
    color: #fff;
  }
  display: flex;
  .h(88);
  justify-content: space-evenly;
  align-items: center;
  .progress-box {
    position: relative;
    .w(220);
    .h(4);
    // background: rgba(0, 0, 0, 0.3);
    background: #fff;
    .progress-contain {
      .w(0);
      .h(5);
      background: #ffcd32;
    }
    .dot {
      position: absolute;
      .left(-8);
      .top(-7);
      width: 16px;
      height: 16px;
      border: 2px solid #fff;
      border-radius: 50%;
      background: #ffcd32;
    }
  }
}
</style>
